from xml.sax.handler import ContentHandler, feature_namespaces
import xml.sax


class XmlHeadler(ContentHandler):
    def __init__(self):
        # 默认读取以一行xml数据的一行为基准，包含标签，属性，值
        self.tag=''      # 标签
        self.attrib=[]   # 属性
        self.content=""  # 值
        self.contents = [] # 节点会存在数据丢失问题，因此，新定义一个变量，存取节点数据
        self.data=[]     # 数据值列表
        self.node_target = True
        self.childnode={}
        self.data_json={}
        self.start_tag='' #初始节点
        self.end_tag=''     #结束节点
        self.a=[]
    def startElement(self, tag, attributes):

        self.tag = tag
        self.start_tag=tag
        self.b = 0
        key_list = attributes.keys()
        value_list=attributes.values()
        # print(key_list,value_list)
        self.attrib=dict(zip(key_list,value_list))
        if self.node_target:
            # self.data_json=
            pass
        # self.inside_text_tag = True
        self.a.append([self.start_tag, self.b])
        
        
    def endElement(self, tag):
        self.end_tag=tag
        if self.start_tag == self.end_tag:
            self.node_target=False
        self.data="".join(self.contents)
        self.data_json = {"tag": self.tag, "attrib": self.attrib, "contents": self.data, "node_targe": self.node_target, "childnode":self.childnode}
        self.contents=[]
        self.b=1
        self.a.append([self.end_tag, self.b])
        print(self.a)
        # print(self.data_json)
    def characters(self, content):
        print(content)
        content = content.replace("&lt;", "<").replace(
            "&gt;", ">").replace("&amp;", "&").replace("&apos;", "'").replace("&quot;", '"')
        self.contents.append(content)
            # https://blog.csdn.net/qq_22766903/article/details/106481917
            # 节点会存在数据丢失问题，因此，新定义一个变量，存取节点数据

    def get_info(self):
        return self.data_json,


xml_path="./xl_workbook.xml"
parser = xml.sax.make_parser()
# turn off namepsaces
parser.setFeature(feature_namespaces, 0)
# 重写 ContextHandler
Handler = XmlHeadler()
parser.setContentHandler(Handler)
parser.parse(xml_path)
Handler.get_info()